package com.migo.api;

import com.migo.annotation.IgnoreAuth;
import com.migo.common.StringSplitUtil;
import com.migo.defence.RtCode;
import com.migo.entity.FirmwareZipEntity;
import com.migo.entity.ZipMatchEntity;
import com.migo.oss.OSSFactory;
import com.migo.service.FirmwareZipService;
import com.migo.service.ZipMatchService;
import com.migo.utils.DateUtil;
import com.migo.utils.HttpClientUtils;
import com.migo.utils.JsonUtils;
import com.migo.utils.R;
import com.migo.validator.Assert;
import com.migo.view.FirmwareEntityView;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * Created by Wes on 2018/12/25.
 */
@RestController
@RequestMapping("/api/zip")
public class ApiZipFirmwareController {

    @Autowired
    OSSFactory ossFactory;


//    @Autowired
//    private FirmwareService firmwareService;  //正式版服务接口

    @Autowired
    private FirmwareZipService firmwareZipService;  //zip固件服务

//    @Autowired
//    private FirmwareDevService firmwareDevService;    //测评版服务接口


    @Autowired
    private ZipMatchService zipMatchService;   //根据不同的APP版本返回对应的match文件

    @Autowired
    StringRedisTemplate redisTemplate;


    @Value("${devUrl}")
    String devUrl;

    @Value("${ossUrl}")
    String ossUrl;


    /**
     * 根据matchType查询match文件
     * test、testb、dev、online
     */
    @IgnoreAuth
    @RequestMapping(value = "queryZipMatch", produces = "application/json;charset=utf-8;")
    public R queryZipMatch(@RequestParam Map<String, String> params) {
        String matchType = params.get("matchType");
        Assert.isBlank(matchType, "Match Type is null");
        ZipMatchEntity zipMatchEntity = zipMatchService.queryByMatchType(matchType);
        if(zipMatchEntity!=null)
        {
            return R.ok().put("match", zipMatchEntity);
        }
        return R.ok();
    }


    /**
     * 固件升级
     */
    @IgnoreAuth
    @RequestMapping(value = "firmwareQuery", produces = "application/json;charset=utf-8;")
    public R firmwareQuery(@RequestParam Map<String, String> params) {
        String hardwareModel = params.get("hardwareModel");
        String equipmentModel = params.get("equipmentModel");
        String hardwareType = params.get("hardwareType");
        String mergeVersion = params.get("mergeVersion");
        try {
            Assert.isBlank(hardwareModel, "hardwareModel is null");
            Assert.isBlank(equipmentModel, "equipmentModel is null");
            Assert.isBlank(hardwareType, "hardwareType is null");
            Assert.isBlank(mergeVersion, "mergeVersion is null");
//            //测评服务器代码
//            return R.ok().put("data", getFirmwareData(hardwareModel,equipmentModel,hardwareType,mergeVersion));
            //正式服务器代码
            String lastVersion = StringSplitUtil.getInstance().getLastVersion(mergeVersion);
            if ("".equals(lastVersion)) {
                return R.ok().put("data", new ArrayList<>());
            }
            params.put("mergeVersion", StringSplitUtil.getInstance().getMergeVersion(mergeVersion));
            params.put("lastVersion", lastVersion);
            List<Map<String, Object>> firmwareMap = firmwareZipService.queryFirmwareMap(params);
            Set<Map<String, Object>> resultMap = checkFirmwareMap(firmwareMap, lastVersion);
            return R.ok().put("data", resultMap);
        } catch (Exception e) {
            return R.error(RtCode.ServerError.getCode(), RtCode.ServerError.getMsg());
        }
    }

    /**
     * 测评版固件查询
     *
     * @param hardwareModel
     * @param equipmentModel
     * @param hardwareType
     * @param mergeVersion
     * @return
     */
    public Object getFirmwareData(String hardwareModel, String equipmentModel, String hardwareType, String mergeVersion) {
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("hardwareModel", hardwareModel));
        formparams.add(new BasicNameValuePair("equipmentModel", equipmentModel));
        formparams.add(new BasicNameValuePair("hardwareType", hardwareType));
        formparams.add(new BasicNameValuePair("mergeVersion", mergeVersion));
        String result = new HttpClientUtils().request(formparams, devUrl + "/api/firmwareQuery");
        JSONObject object = JSONObject.fromObject(result);
        return object.get("data");
    }


    public Set<Map<String, Object>> checkFirmwareMap(List<Map<String, Object>> firmwareMap, String lastVersion) {
        Set<Map<String, Object>> result = new HashSet<Map<String, Object>>();
//        List<Map<String, Object>> result  = new ArrayList<>();
        for (int i = 0; i < firmwareMap.size(); i++) {
            Map<String, Object> map = firmwareMap.get(i);
            String result_version = map.get("firmware_latest_version_code").toString();
            Map<String, String> valMap = StringSplitUtil.getInstance().getLastVersionMap(result_version, "-");
            Map<String, String> latestMap = StringSplitUtil.getInstance().getLastVersionMap(lastVersion, "-");
            for (Map.Entry<String, String> entry : latestMap.entrySet()) {
                System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
                boolean b = valMap.containsKey(entry.getKey());
                if (b) {
                    boolean val = entry.getValue().equals(valMap.get(entry.getKey()));
                    if (!val) {
                        result.add(map);
                    }
                }
            }

        }
        return result;
    }


    /**
     * 查询Match redis key
     */
    @IgnoreAuth
    @RequestMapping(value = "queryMatchFileKey", produces = "application/json;charset=utf-8;")
    public R queryMatchFileKey(@RequestParam Map<String, String> params) {
        String matchType = params.get("matchType");
        try {
            Assert.isBlank(matchType, "Match Type is null");
            boolean b = redisTemplate.hasKey(matchType);
            if (b) {
                String fileKey = redisTemplate.boundValueOps(matchType).get();
                return R.ok().put("key", fileKey);
            }
            return R.ok("没有查询到文件验证码！");
        } catch (Exception e) {
            return R.error(RtCode.ServerError.getCode(), RtCode.ServerError.getMsg());
        }
    }


    /**
     * 检索Push Match redis key
     */
    @IgnoreAuth
    @RequestMapping(value = "pushMatchFileKey", produces = "application/json;charset=utf-8;")
    public R pushMatchFileKey(@RequestParam Map<String, String> params) {
        String test = params.get("test");
        String testb = params.get("testb");
        String dev = params.get("dev");
        String online = params.get("online");
        redisTemplate.boundValueOps("test").set(test);
        redisTemplate.boundValueOps("testb").set(testb);
        redisTemplate.boundValueOps("dev").set(dev);
        redisTemplate.boundValueOps("online").set(online);
        return R.ok();
    }


    /**
     * 遥控器升级
     */
    @IgnoreAuth
    @RequestMapping(value = "remoteControllerFirmwareQuery", produces = "application/json;charset=utf-8;")
    public R remoteControllerFirmwareQuery(@RequestParam Map<String, String> params) {
        String mergeVersion = params.get("mergeVersion");
        try {
            Assert.isBlank(mergeVersion, "mergeVersion is null");
//            //测评服务器数据返回
//            return R.ok().put("data", getW4RemoteData(mergeVersion));
//            正式服务器数据返回代码
            List<Map<String, Object>> firmwares = queryFirmware(mergeVersion);
            return R.ok().put("data", firmwares);
        } catch (Exception e) {
            return R.error(RtCode.ServerError.getCode(), RtCode.ServerError.getMsg());
        }
    }

    /**
     * W4遥控器升级
     *
     * @param mergeVersion
     * @return
     */
    public Object getW4RemoteData(String mergeVersion) {
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("mergeVersion", mergeVersion));
        String result = new HttpClientUtils().request(formparams, devUrl + "/api/remoteControllerFirmwareQuery");
        JSONObject object = JSONObject.fromObject(result);
        return object.get("data");
    }


    /**
     * 船体固件完整性校验
     */
    @IgnoreAuth
    @RequestMapping(value = "powerDolphinZipCheck", produces = "application/json;charset=utf-8;")
    public R powerDolphinZipCheck(@RequestParam Map<String, String> params) {
        String key = params.get("key");
        try {
            Assert.isBlank(key, "key is null");
//            //测评服务器代码
//            return R.ok().put("data", getDolphinZipCheckData(key));
//            正式代码--
            String md5Key = redisTemplate.boundValueOps(key).get();
            //构造返回结果
            Map<String, String> resultMap = new HashMap<>();
            resultMap.put("val", md5Key);
            return R.ok().put("data", resultMap);
        } catch (Exception e) {
            return R.error(RtCode.ServerError.getCode(), RtCode.ServerError.getMsg());
        }
    }

    /**
     * 船体固件完整性校验
     *
     * @param key
     * @return
     */
    public Object getDolphinZipCheckData(String key) {
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("key", key));
        String result = new HttpClientUtils().request(formparams, devUrl + "/api/powerDolphinZipCheck");
        JSONObject object = JSONObject.fromObject(result);
        return object.get("data");
    }


    /**
     * AP03整机固件升级
     */
    @IgnoreAuth
    @RequestMapping(value = "eggXBodyUpdate", produces = "application/json;charset=utf-8;")
    public R eggXBodyUpdate(@RequestParam Map<String, String> params) {
        String mergeVersion = params.get("mergeVersion");
        try {
            Assert.isBlank(mergeVersion, "mergeVersion is null");
//            //测评服务获取固件数据
//            return getEggAllData(mergeVersion);
//            添加config 文件-----------正式环境代码
            StringBuffer conf = new StringBuffer(mergeVersion);
            conf.append("_config-" + System.currentTimeMillis());
//            params.put("mergeVersion", StringSplitUtil.getInstance().getMergeVersion(conf.toString()));
            List<Map<String, Object>> firmwares = queryAP03Firmware(conf.toString());
            if (firmwares.size() > 1) {
                //打包配置文件
                return R.ok().put("data", firmwares);
            }
            //打包配置文件
            return R.ok();
        } catch (Exception e) {
            return R.error(RtCode.ServerError.getCode(), RtCode.ServerError.getMsg());
        }
    }


    /**
     * 测评服务器 AP03整机固件升级数据返回
     *
     * @param mergeVersion
     * @return
     */
    public R getEggAllData(String mergeVersion) {
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("mergeVersion", mergeVersion));
        String result = new HttpClientUtils().request(formparams, devUrl + "/api/powerEggMiniFirmwareQuery");
        JSONObject obj = JSONObject.fromObject(result);
        if (obj.has("data")) {
            JSONArray array = JSONArray.fromObject(obj.get("data"));
//            array = ProxyData(array);
            List<Map<String, Object>> proxyList = ProxyData(array);
            if (array.size() > 0) {
                return R.ok().put("data", proxyList);
            }
        }
        return R.ok();
    }


    public List<Map<String, Object>> ProxyData(JSONArray array) {
        List<Map<String, Object>> proxyList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        for (int i = 0; i < array.size(); i++) {
            try {
                map = JsonUtils.getMapFromJson(JsonUtils.getJSONString(array.get(i)));
                String val = JsonUtils.getJSONString(map.get("firmware_description"));
                map.put("firmware_description", val);
                proxyList.add(map);
            } catch (Exception e) {
            }
        }
        return proxyList;
    }


    /**
     * AP03遥控器升级
     */
    @IgnoreAuth
    @RequestMapping(value = "eggXRemoteControlUpdate", produces = "application/json;charset=utf-8;")
    public R eggXRemoteControlUpdate(@RequestParam Map<String, String> params) {
        String hardwareModel = params.get("hardwareModel");
        String equipmentModel = params.get("equipmentModel");
        String hardwareType = params.get("hardwareType");
        String lastVersion = params.get("lastVersion");
        try {
            Assert.isBlank(hardwareModel, "hardwareModel is null");
            Assert.isBlank(equipmentModel, "equipmentModel is null");
            Assert.isBlank(hardwareType, "hardwareType is null");
            Assert.isBlank(lastVersion, "Version is null");
//            //测评服务器
//            return R.ok().put("data", getEggRemoteData(hardwareModel,equipmentModel,hardwareType,lastVersion));
            //正式固件注释
            List<Map<String, Object>> firmwareMap = firmwareZipService.queryFirmwareMap(params);
            return R.ok().put("data", firmwareMap);

        } catch (Exception e) {
            return R.error(RtCode.ServerError.getCode(), RtCode.ServerError.getMsg());
        }
    }


    /**
     * 测评服务器AP03遥控器升级固件数据返回
     *
     * @param hardwareModel
     * @param equipmentModel
     * @param hardwareType
     * @param lastVersion
     * @return
     */
    public Object getEggRemoteData(String hardwareModel, String equipmentModel, String hardwareType, String lastVersion) {
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("hardwareModel", hardwareModel));
        formparams.add(new BasicNameValuePair("equipmentModel", equipmentModel));
        formparams.add(new BasicNameValuePair("hardwareType", hardwareType));
        formparams.add(new BasicNameValuePair("lastVersion", lastVersion));
        String result = new HttpClientUtils().request(formparams, devUrl + "/api/powerEggRemoteFirmwareQuery");
        JSONObject object = JSONObject.fromObject(result);
        return object.get("data");
    }


    /**
     * AP03  Model升级
     */
    @IgnoreAuth
    @RequestMapping(value = "eggXModelUpdate", produces = "application/json;charset=utf-8;")
    public R eggXModelUpdate(@RequestParam Map<String, String> params) {
        String hardwareModel = params.get("hardwareModel");
        String equipmentModel = params.get("equipmentModel");
        String hardwareType = params.get("hardwareType");
        String lastVersion = params.get("lastVersion");
        try {
            Assert.isBlank(hardwareModel, "hardwareModel is null");
            Assert.isBlank(equipmentModel, "equipmentModel is null");
            Assert.isBlank(hardwareType, "hardwareType is null");
            Assert.isBlank(lastVersion, "Version is null");
//            //测评服务器获取数据
//            return R.ok().put("data", getEggModelData(hardwareModel,equipmentModel,hardwareType,lastVersion));
            //正式服务器获取数据
            List<FirmwareZipEntity> resultList = getModelList(params);
            return R.ok().put("data", getModelViewList(resultList));
        } catch (Exception e) {
            return R.error(RtCode.ServerError.getCode(), RtCode.ServerError.getMsg());
        }
    }

    /**
     * 测评服务器Model固件数据返回
     *
     * @param hardwareModel
     * @param equipmentModel
     * @param hardwareType
     * @param lastVersion
     * @return
     */
    public Object getEggModelData(String hardwareModel, String equipmentModel, String hardwareType, String lastVersion) {
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("hardwareModel", hardwareModel));
        formparams.add(new BasicNameValuePair("equipmentModel", equipmentModel));
        formparams.add(new BasicNameValuePair("hardwareType", hardwareType));
        formparams.add(new BasicNameValuePair("lastVersion", lastVersion));
        String result = new HttpClientUtils().request(formparams, devUrl + "/api/powerEggModelFirmwareQuery");
        JSONObject object = JSONObject.fromObject(result);
        return object.get("data");
    }

    /**
     * 给APP重新组装数据
     *
     * @param resultList
     * @return
     */
    public List<FirmwareEntityView> getModelViewList(List<FirmwareZipEntity> resultList) {
        //增加config
        Map<String, String> params = new HashMap<>();
        params.put("hardwareModel", "config");
        params.put("equipmentModel", "AP03");
        params.put("hardwareType", "config");
        params.put("lastVersion", "000");
        List<FirmwareZipEntity> config = firmwareZipService.queryModelList(params);
        List<FirmwareEntityView> result = new ArrayList<>();

        int len = resultList.size();
        if (len > 0) //如果发现MODEL固件需要返回的话才返回config
        {
            resultList.add(config.get(0));
        }
        for (int i = 0; i < resultList.size(); i++) {
            FirmwareZipEntity firmwareEntity = resultList.get(i);
            FirmwareEntityView view = new FirmwareEntityView();
            view.setAdd_time(firmwareEntity.getAddTime());
            view.setEquipment_model(firmwareEntity.getEquipmentModel());
            view.setFirmware_download_addr(firmwareEntity.getFirmwareDownloadAddr());
            view.setFirmware_latest_version_code(firmwareEntity.getFirmwareLatestVersionCode());
            view.setFirmware_size(firmwareEntity.getFirmwareSize());
            view.setHardware_model(firmwareEntity.getHardwareModel());
            view.setHardware_type(firmwareEntity.getHardwareType());
            view.setIs_mandatory_upgrade(firmwareEntity.getIsMandatoryUpgrade());
            view.setRow_id(firmwareEntity.getRowId());
            view.setId(firmwareEntity.getId());
            view.setStatus(firmwareEntity.getStatus());
            result.add(view);
        }
        return result;
    }


    public static void main(String[] args) {

        try {
            Map<String, String> param = new HashMap<>();
            param.put("hardwareModel", "DL");
            param.put("equipmentModel", "AP03RC");
            param.put("hardwareType", "DL");
            param.put("lastVersion", "1.18.50");
            List<NameValuePair> formparams = new ArrayList<NameValuePair>();
            formparams.add(new BasicNameValuePair("hardwareModel", "DL"));
            formparams.add(new BasicNameValuePair("equipmentModel", "AP03RC"));
            formparams.add(new BasicNameValuePair("hardwareType", "DL"));
            formparams.add(new BasicNameValuePair("lastVersion", "1.18.50"));
            String result = new HttpClientUtils().request(formparams, "http://supplier.powervision.me:9999/api/powerEggRemoteFirmwareQuery");
            JSONObject object = JSONObject.fromObject(result);
            String val = object.get("data").toString();
//            String json = JsonUtils.getJSONString(param);
//            String result = HttpClientUtils.post("http://supplier.powervision.me:9999/api/powerEggRemoteFirmwareQuery",json);
            System.out.println(val);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询固件订单清单
     *
     * @return
     */
    public List<FirmwareZipEntity> getModelList(Map<String, String> params) {
        List<FirmwareZipEntity> resultList = firmwareZipService.queryModelList(params);

        String[] lastVersions = params.get("lastVersion").split("\\.");
        Integer userMaxVersion = Integer.parseInt(lastVersions[0]);
        Integer userMiddleVersion = Integer.parseInt(lastVersions[1]);
        Integer userMinVersion = Integer.parseInt(lastVersions[2]);

        int len = resultList.size();
        int[] mbArray = new int[len];
        int[] mpArray = new int[len];
        int[] mpMinArray = new int[len];
        Map<String, FirmwareZipEntity> allMap = new HashMap<>();
        for (int i = 0; i < len; i++) {
            FirmwareZipEntity firmwareEntity = resultList.get(i);
            allMap.put(firmwareEntity.getFirmwareLatestVersionCode(), firmwareEntity);
            String[] versions = firmwareEntity.getFirmwareLatestVersionCode().split("\\.");
            Integer val = Integer.parseInt(versions[0]);
            mbArray[i] = val;
        }
        int maxVersion = Arrays.stream(mbArray).max().getAsInt(); //最大的
        for (int j = 0; j < len; j++) {
            FirmwareZipEntity firmwareEntity = resultList.get(j);
            String[] versions = firmwareEntity.getFirmwareLatestVersionCode().split("\\.");
            Integer val = Integer.parseInt(versions[0]);
            Integer val2 = Integer.parseInt(versions[1]);
            if (maxVersion == val) {
                mpArray[j] = val2;
            }
        }
        int middleVersion = Arrays.stream(mpArray).max().getAsInt(); //中间的
        for (int k = 0; k < len; k++) {
            FirmwareZipEntity firmwareEntity = resultList.get(k);
            String[] versions = firmwareEntity.getFirmwareLatestVersionCode().split("\\.");
            Integer val = Integer.parseInt(versions[0]);
            Integer val2 = Integer.parseInt(versions[1]);
            Integer val3 = Integer.parseInt(versions[2]);
            if (maxVersion == val && middleVersion == val2) {
                mpMinArray[k] = val3;
            }
        }
        int minVersion = Arrays.stream(mpMinArray).max().getAsInt(); //中间的
        String mpMaxVersion = maxVersion + "" + middleVersion + "" + minVersion;
        String userMpVersion = userMaxVersion + "" + userMiddleVersion + "" + userMinVersion;

        List<FirmwareZipEntity> result = new ArrayList<>();

        String mpCode = maxVersion + "." + middleVersion + "." + minVersion;
        String mbCode = maxVersion + ".0.0";
        //找到数据库中最新的数据返回
        FirmwareZipEntity mb = allMap.get(mbCode);
        FirmwareZipEntity mp = allMap.get(mpCode);


        if (Integer.parseInt(userMpVersion) < Integer.parseInt(mpMaxVersion)) {
            if (userMaxVersion < maxVersion) {
                result.add(mb);
            }
            result.add(mp);
        } else if (Integer.parseInt(userMpVersion) == Integer.parseInt(mpMaxVersion)) {
            if (allMap.containsKey(params.get("lastVersion"))) {
//                result.add(mp);
            }
        }
        return result;
    }


    /**
     * 船体固件升级
     */
    @IgnoreAuth
    @RequestMapping(value = "powerDolphinFirmwareQuery", produces = "application/json;charset=utf-8;")
    public R powerDolphinFirmwareQuery(@RequestParam Map<String, String> params) {
        String mergeVersion = params.get("mergeVersion");
        try {
            Assert.isBlank(mergeVersion, "mergeVersion is null");
            //添加config 文件
            StringBuffer conf = new StringBuffer(mergeVersion);
            conf.append("_config-" + System.currentTimeMillis());
//            params.put("mergeVersion", StringSplitUtil.getInstance().getMergeVersion(conf.toString()));
            List<Map<String, Object>> firmwares = queryFirmware(conf.toString());
            if (firmwares.size() > 1) {
                //打包配置文件
                return R.ok().put("data", firmwares);
            }
            //打包配置文件
            return R.ok();
        } catch (Exception e) {
            return R.error(RtCode.ServerError.getCode(), RtCode.ServerError.getMsg());
        }
    }


    public Map getZipName(List<Map<String, Object>> firmwares) throws Exception {

        Map<String, String> resultMap = new HashMap<>();
        StringBuffer zipName = new StringBuffer();
        StringBuffer keys = new StringBuffer("app/20190125/update.conf,");//只要有更新数据默认全部打包 update.conf
        int len = firmwares.size();
        for (int i = 0; i < len; i++) {
            Map map = JsonUtils.getMapFromJson(JsonUtils.getJSONString(firmwares.get(i)));
            if (i == 0) {
                zipName.append(map.get("equipment_model").toString()).append("_");
            }
            String name = map.get("hardware_model").toString();
            String version = map.get("firmware_latest_version_code").toString();
            zipName.append(name + "-" + version);
            //keys
            keys.append(map.get("firmware_download_addr").toString());
            if (i < len - 1) {
                zipName.append("_");
                keys.append(",");
            }
        }
        resultMap.put("zipName", zipName.toString());
        resultMap.put("keys", keys.toString());
        return resultMap;
    }


    /**
     * 当前版本主要用于AP03的整机固件 升级，业务需求临时变更；
     * 固件-升级过程不能够跳过版本-会存在问题
     * 所有版本都存储历史记录，进行 版本时间匹配，超过当前版本上传时间的全部更新返回；
     *
     * @param mergeVersion
     * @return
     */
    public List<Map<String, Object>> queryAP03Firmware(String mergeVersion) {
//        String str = "AP03_MC-1.0.2_FC-1901241234_DL-1.3.39"; //事例测试数据
        String[] paramArray = mergeVersion.split("_");
        String product = paramArray[0];
        Map<String, String> firmwareMap = new HashMap<>();
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (int i = 1; i < paramArray.length; i++) {
            String[] firmwareArr = paramArray[i].split("-");
            firmwareMap.put(firmwareArr[0], firmwareArr[1]);
            if ("0".equals(firmwareArr[1].toString())) {
                continue;
            }
            Map<String, String> params = new HashMap<>();
            params.put("hardwareType", firmwareArr[0]);
            params.put("hardwareModel", firmwareArr[0]);
            params.put("lastVersion", firmwareArr[1]);
            params.put("equipmentModel", product);
            List<FirmwareZipEntity> groupResult = firmwareZipService.queryFirmwareObjects(params);  //获取


            Map<String, List<FirmwareZipEntity>> groupMap = groupResultFirmware(groupResult, firmwareArr[1]);


            if (groupMap != null) {
                List<FirmwareZipEntity> yesResult = groupMap.get("1");
                List<FirmwareZipEntity> noResult = groupMap.get("0");

                String version = "";

                if (yesResult != null && yesResult.size() > 0) {
                    //查找比用户版本大一个版本需要强制升级的数据
                    version = getResultVersion(yesResult, 1);
                    System.out.println(version);
                } else if (noResult != null && noResult.size() > 0) {
                    //查找最新的版本
                    version = getResultVersion(noResult, 0);
                    System.out.println(version);
                }
                params.put("lastVersion", version);
                List<Map<String, Object>> list = firmwareZipService.queryNextVersionList(params);
                resultList.addAll(list);
            }
        }
        return resultList;
    }

    /**
     * 获取 强制升级的next 版本号
     *
     * @param groupResult
     * @return
     */
    public String getResultVersion(List<FirmwareZipEntity> groupResult, int status) {
        String version = "";
        Map<String, Integer> entityMap = new HashMap<>();
        int len = groupResult.size();
        //group
        for (int i = 0; i < len; i++) {
            FirmwareZipEntity groupEntity = groupResult.get(i);
            Long diffVal = DateUtil.timeDiff(DateUtil.string2Date(DateUtil.getNow(), DateUtil.COMMON_DATETIME), DateUtil.string2Date(groupEntity.getAddTime(), DateUtil.COMMON_DATETIME));
            entityMap.put(groupEntity.getFirmwareLatestVersionCode(), diffVal.intValue());
        }
        for (Map.Entry<String, Integer> entry : entityMap.entrySet()) {
            String key = entry.getKey();
            Integer value = entry.getValue();
            if (status == 1) {
                if (value == getMaxVal(entityMap)) {
                    version = key;
                }
            } else {
                if (value == getMinVal(entityMap)) {
                    version = key;
                }
            }
        }
        return version;
    }

    /**
     * 求Map<K,V>中Key(键)的最大值
     *
     * @param map
     * @return
     */
    public static Object getMinVal(Map<String, Integer> map) {
        if (map == null) return null;
        Collection<Integer> c = map.values();
        Object[] obj = c.toArray();
        Arrays.sort(obj);
        return obj[0];
    }

    /**
     * 求Map<K,V>中Key(键)的最大值
     *
     * @param map
     * @return
     */
    public static Object getMaxVal(Map<String, Integer> map) {
        if (map == null) return null;
        Collection<Integer> c = map.values();
        Object[] obj = c.toArray();
        Arrays.sort(obj);
        return obj[obj.length - 1];
    }

    /**
     * 对查询出来的所有结果进行处理
     *
     * @param groupResult
     * @return
     */
    public Map<String, List<FirmwareZipEntity>> groupResultFirmware(List<FirmwareZipEntity> groupResult, String userVersion) {
        Map<String, List<FirmwareZipEntity>> groupMap = new HashMap<>();

        Map<String, FirmwareZipEntity> entityMap = new HashMap<>();

        List<FirmwareZipEntity> yResult = new ArrayList<>();
        List<FirmwareZipEntity> nResult = new ArrayList<>();

        int len = groupResult.size();
        //group
        for (int i = 0; i < len; i++) {
            FirmwareZipEntity groupEntity = groupResult.get(i);
            entityMap.put(groupEntity.getFirmwareLatestVersionCode(), groupEntity);
        }

        //没有记录的版本--给一个虚拟时间
        String initTime = "2019-10-20 11:27:33";
        Map<String, FirmwareZipEntity> tempMap = new HashMap<>();
        if (entityMap.containsKey(userVersion)) {
            FirmwareZipEntity mapEntity = entityMap.get(userVersion);
            initTime = mapEntity.getAddTime();
        }

        Map<Long, FirmwareZipEntity> maxMap = new HashMap<>();

        for (Map.Entry<String, FirmwareZipEntity> entry : entityMap.entrySet()) {
            String key = entry.getKey();
            FirmwareZipEntity value = entry.getValue();
            Long diffVal = DateUtil.timeDiff(DateUtil.string2Date(value.getAddTime(), DateUtil.COMMON_DATETIME), DateUtil.string2Date(initTime, DateUtil.COMMON_DATETIME));
            if ((diffVal.toString().matches("[0-9]+")) && diffVal.doubleValue() > 0) {
                tempMap.put(key, value);
            }
            maxMap.put(diffVal, value);
        }
        if (tempMap.size() == 0) {
            return null;
        }

        //遍历大版本固件--查找是否需要强制升级
        for (int j = 0; j < len; j++) {
            FirmwareZipEntity resultEntity = groupResult.get(j);
            if (tempMap.containsKey(resultEntity.getFirmwareLatestVersionCode())) {
                if (resultEntity.getIsMandatoryUpgrade() == 1) {
                    yResult.add(resultEntity);
                } else {
                    nResult.add(resultEntity);
                }
            }

        }

        String maxVersion = getMaxVersion(maxMap);
        //在过滤一遍获取最大的版本  yResult 不需要过滤
        nResult = getResult(nResult, maxVersion);

        groupMap.put("1", yResult);

        groupMap.put("0", nResult);

        return groupMap;
    }


    public String getMaxVersion(Map<Long, FirmwareZipEntity> maxMap) {
        List<Long> list = new ArrayList<Long>();
        for (Long value : maxMap.keySet()) {
            list.add(value);
        }
        Long min = Collections.max(list);
        return maxMap.get(min).getFirmwareLatestVersionCode();
    }


    public List<FirmwareZipEntity> getResult(List<FirmwareZipEntity> valList, String maxVersion) {

        List<FirmwareZipEntity> lastList = new ArrayList<>();
        for (int i = 0; i < valList.size(); i++) {
            FirmwareZipEntity entity = valList.get(i);
            if (entity.getFirmwareLatestVersionCode().equals(maxVersion)) {
                lastList.add(entity);
            }
        }
        return lastList;
    }


    public List<Map<String, Object>> queryFirmware(String mergeVersion) {
//        String str = "PVW4_MC-1.0.2_FC-1901241234_DL-1.3.39"; //事例测试数据
        String[] paramArray = mergeVersion.split("_");
        String product = paramArray[0];
        Map<String, String> firmwareMap = new HashMap<>();
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (int i = 1; i < paramArray.length; i++) {
            String[] firmwareArr = paramArray[i].split("-");
            firmwareMap.put(firmwareArr[0], firmwareArr[1]);
            if ("0".equals(firmwareArr[1].toString())) {
                continue;
            }
            Map<String, String> params = new HashMap<>();
            params.put("hardwareType", firmwareArr[0]);
            params.put("hardwareModel", firmwareArr[0]);
            params.put("lastVersion", firmwareArr[1]);
            params.put("equipmentModel", product);
            List<Map<String, Object>> list = firmwareZipService.queryFirmwareMap(params);
            resultList.addAll(list);
        }
        return resultList;
    }


}
